from datetime import datetime, timezone, timedelta

from dao.es_dao.card_dao import get_card
from dao.es_dao.p_health_log_dao import save_all_health
from utils.mongo_util import db


async def query_health_data():
    """
    查询指定时间范围内的健康数据
    时间范围：UTC时间2025-06-10 01:50:15 至 2025-06-11 04:28:15
    对应北京时间：2025-06-10 09:50:15 至 2025-06-11 12:28:15
    """
    try:
        # 1. 创建MongoDB连接
      # 替换为实际集合名
        # 2. 准备查询条件
        query = {
            "action": "health",
            "date": {
                "$gt": datetime(2025, 6, 10, 1, 50, 15, tzinfo=timezone.utc),
                "$lt": datetime(2025, 6, 11, 4, 28, 15, tzinfo=timezone.utc)
            }
        }
        # 3. 执行查询
        results = list(db.wristband_log.find(query))
        i = 0
        for result in results:
            if i > 3:
                intensity = await query_work_time_last(result['date'], result['device_id'])
                await handle_health(result, intensity)
            i += 1
        return results

    except Exception as e:
        print(f"数据库查询错误1: {e}")
        return []


async def query_work_time_last(date: datetime, imei: str):
    """
    查询指定时间范围内的健康数据
    时间范围：UTC时间2025-06-10 01:50:15 至 2025-06-11 04:28:15
    对应北京时间：2025-06-10 09:50:15 至 2025-06-11 12:28:15
    """
    try:
        # 1. 创建MongoDB连接
        # 2. 准备查询条件
        query = {
            "imei": imei,
            "date": {
                "$lt": date
            }
        }
        # 3. 执行查询
        results = list(db.work_time.find(query).sort("date", -1).limit(1))
        if len(results) > 0:
            is_less = is_less_than_10_minutes(results[0]['date'], date)
            if is_less:
                return results[0]
            else:
                return {'intensity': -1, 'step': 0}

    except Exception as e:
        print(f"数据库查询错误2: {e}")
        return []


async def handle_health(data: dict, intensity: dict):
    _id, card_doc = await get_card(data['device_id'])
    if card_doc is not None:
        await save_all_health(data, card_doc['dataAuthority'], intensity)


def is_less_than_10_minutes(dt1: datetime, dt2: datetime) -> bool:
    """
    判断两个datetime对象的时间差是否小于10分钟

    参数:
        dt1: 第一个datetime对象
        dt2: 第二个datetime对象

    返回:
        bool: 时间差小于10分钟返回True，否则返回False
    """
    # 计算绝对时间差（避免负值）
    time_diff = abs(dt2 - dt1)

    # 创建10分钟的timedelta对象
    ten_minutes = timedelta(minutes=10)

    # 比较时间差是否小于10分钟
    return time_diff < ten_minutes
